package com.example.springboot.filter;


import com.example.springboot.security.TokenManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 授权过滤器
 * @default
**/
public class TokenAuthFilter extends BasicAuthenticationFilter {

    private TokenManager tokenManager;
    private RedisTemplate<String,String> redisTemplate;

    public TokenAuthFilter(AuthenticationManager authenticationManager,TokenManager tokenManager,RedisTemplate<String,String> redisTemplate) {
        super(authenticationManager);
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 获取当前认证成功用户权限信息
        UsernamePasswordAuthenticationToken upat = getAuthentication(request);
        // 判断如果又权限信息，放到权限上下文中
        if(upat != null){
            SecurityContextHolder.getContext().setAuthentication(upat);
        }
        chain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request){
        String token = request.getHeader("token");
        if(token != null){
            String name = tokenManager.getUserInfo(token);
            // 获取权限
            List<String> s = redisTemplate.opsForList().range(token,0,-1);
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            for (String perm : s){
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(perm);
                authorities.add(authority);
            }
            return new UsernamePasswordAuthenticationToken(name,token,authorities);
        }
        return null;
    }

}
